<?php

namespace App\Models;

use Illuminate\Http\Request;
use DB;

class AdminRole extends Model
{
	private static $_obj;

	public static function getInstance()
	{
		if (!self::$_obj instanceof self) {
			self::$_obj = new self;
		}
		return self::$_obj;
	}

	/**
	 * 关联到模型的数据表
	 * 默认规则是模型类名的复数作为与其对应的表名
	 * @var  string
	 * @author  朱旭 
	 */
	protected $table = 'admin_role';

	/**
	 * 表名模型是否应该被打上时间戳
	 * @var  bool
	 * @author 朱旭
	 */
	public $timestamps = false;

	/**
	 * 批量赋值黑名单
	 * @var array
	 */
	protected $guarded = [];

	/**
	 * AdminRole关联表添加操作
	 */
	public function addAdminRole(array $rid, $aid)
	{
		if (!$rid || !$aid) return false;
		$data = [];
		foreach ($rid as $key => $val) {
			$data[] = [
				'rid' => $val,
				'aid' => $aid,
			];
		}
		$result = $this->insert($data);
		return $result;
	}

	/**
	 * 根据aid获取节点权限列表
	 * @param int $id 管理员表唯一标识
	 */
	public function getRoleListByAid($aid)
	{
		$data = self::where('aid',$aid)->get();
		$res = [];
		foreach ($data as $key => $val) {
			$res[] = $val->rid;
		}
		return $res;
	}

	/**
	 * 根据aid删除角色关联表
	 * @param int $aid 管理员id
	 */
	public function delAdminRoleByAid($aid)
	{
		$res = self::where('aid',$aid)->delete();
		return $res;
	}

	/**
	 * 根据角色id删除关联表o
	 * @param int $rid 角色id
	 */
	public function delAdminRoleByRid($rid)
	{
		$res = self::where("rid",$rid)->delete();
		return $res;
	}

	/**
	 * 通过关联查询获取权限节点
	 */
	public function getNodeByJoin($aid)
	{
		$result = self::select("node.*")
			->where([['status',1],['aid',$aid]])
			->join("role_node", 'admin_role.rid', '=', 'role_node.rid')
			->join("node", 'role_node.nid', '=', 'node.id')
			->get();
		return $result;
	}
}